/**
 * info controller
 */

import { factories } from '@strapi/strapi'

export default factories.createCoreController('api::info.info', ({ strapi }) => ({
  async save(ctx) {
    const authUser = ctx.state.user;
    if (!authUser) {
      return ctx.unauthorized();
    }
    try {
      const body = ctx.request.body;

      const isExist = await strapi.documents("api::info.info").findFirst({
        filters: {
          user: authUser.id,
        }
      });

      if (isExist) {
        const query: any = {
          documentId: isExist.documentId,
          data: {
            ...body
          },
        };
        const result = await strapi.documents("api::info.info").update(query);
        return result;
      } else {
        const query: any = {
          data: {
            user: authUser.id,
            ...body
          },
          status: "draft"
        }
        const result = await strapi.documents("api::info.info").create(query);
        return result;
      }
    } catch (e) {
      return ctx.badRequest();
    }
  }
}));
